package com.chongyahhh.security.security.configs.wechat;

import com.chongyahhh.security.security.common.AuthenticationProcessor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author chongyahhh
 * 微信登录处理器
 */
public class WechatAuthenticationProcessor implements AuthenticationProcessor {
    private final String CODE = "code";
    private final String OPEN_ID = "openId";

    public WechatAuthenticationProcessor(){}

    @Override
    public Authentication preAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        String code = this.obtainCode(request);
        // 获取用户的 openId
        String openId = this.obtainOpenId(code);

        // 这个只做登录信息使用
        WechatAuthentication authentication = new WechatAuthentication();
        // 保存 openId 为附加属性
        authentication.setExtra(OPEN_ID, openId);

        return authentication;
    }

    @Override
    public void postAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException, IOException, ServletException {
        // do nothing
    }

    private String obtainCode(HttpServletRequest request) {
        return request.getParameter(CODE);
    }

    /**
     * 访问微信接口，获取 openId
     * @param code
     * @return
     */
    private String obtainOpenId(String code){
        // 访问微信接口，获取 openId
        return "lol";
    }

}
